﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.DynamicData;
using System.Collections.Specialized;

namespace Catalyst.Web.DynamicData
{
    /// <summary>
    /// The base class used by UserControls that implements a like comparisson. 
    /// </summary>
    public abstract class LikeFilterUserControlBase : FilterTemplateUserControlBase
    {
        public abstract LikeExpressionParameter.LikeType Like { get; set; }
        public abstract string Value { get; set; }

        public override IEnumerable<Parameter> GetWhereParameters(IDynamicDataSource dataSource)
        {
            yield return new LikeExpressionParameter() { Name = Column.Name, Like = Like, Value = Value }; 
        }

        public override void LoadQueryStringParameters(NameValueCollection parameters)
        {
            string likeType = parameters[string.Format("{0}_Like", Column.Name)];
            string value = parameters[string.Format("{0}_Value", Column.Name)];
            
            if (!string.IsNullOrEmpty(likeType) && Enum.IsDefined(typeof(LikeExpressionParameter.LikeType), likeType))
            {
                Like = (LikeExpressionParameter.LikeType)Enum.Parse(typeof(LikeExpressionParameter.LikeType), likeType);
                Value = value;
            }
        }

        public override NameValueCollection SaveQueryStringParameters()
        {
            NameValueCollection parameters = new NameValueCollection();
            parameters.Add(string.Format("{0}_Like", Column.Name), Like.ToString());
            parameters.Add(string.Format("{0}_Values", Column.Name), Value);
            return parameters;
        }

        public override void Clear()
        {
            Value = string.Empty;
        }
    }
}
